//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package upgrade

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/api_coll_dao"
	"atomgit.com/openlinksaas/api-server/dao/comment_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas/api-server/dao/watch_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_entry_api"
)

type UpToVer28 struct{}

func (up *UpToVer28) Exec(ctx context.Context) error {
	//迁移apicoll
	err := up.processApiColl(ctx)
	if err != nil {
		return err
	}
	//迁移watch
	err = watch_dao.MyWatchDao.Upgrade(ctx)
	if err != nil {
		return err
	}
	//迁移comment
	err = comment_dao.CommentDao.Upgrade(ctx)
	if err != nil {
		return err
	}
	err = comment_dao.UnReadDao.RemoveApiCollTarget(ctx)
	if err != nil {
		return err
	}
	return dao.VersionDao.Set(ctx, dao.VERSION_KEY_SCHEMA, 28)
}

func (up *UpToVer28) processApiColl(ctx context.Context) error {
	apiCollItemList, err := api_coll_dao.InfoDao.ListAllForUpgrade(ctx)
	if err != nil {
		return err
	}
	for _, apiCollItem := range apiCollItemList {
		exist, err := project_entry_dao.EntryDao.Exist(ctx, apiCollItem.ApiCollId, apiCollItem.ProjectId)
		if err != nil {
			return err
		}
		if exist {
			continue
		}
		err = project_entry_dao.EntryDao.Insert(ctx, &project_entry_dao.EntryInfoDbItem{
			EntryId:        apiCollItem.ApiCollId,
			ProjectId:      apiCollItem.ProjectId,
			ParentFolderId: "",
			EntryType:      uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_API_COLL),
			EntryTitle:     apiCollItem.Name,
			MarkSys:        false,
			TagIdList:      []string{},
			EntryPerm: project_entry_dao.EntryPermDbItem{
				UpdateForAll:          true,
				ExtraUpdateUserIdList: []string{},
			},
			ExtraApiCollInfo: &project_entry_dao.ExtraApiCollInfoDbItem{
				ApiCollType: apiCollItem.ApiCollType,
				DefaultAddr: apiCollItem.DefaultAddr,
			},
			CreateUserId: apiCollItem.CreateUserId,
			CreateTime:   apiCollItem.CreateTime,
			UpdateUserId: apiCollItem.UpdateUserId,
			UpdateTime:   apiCollItem.UpdateTime,
		})
		if err != nil {
			return err
		}
	}
	return nil
}
